import PIL
from django.shortcuts import render

# Create your views here.
from django.views import View
from django.http import HttpResponse
from libs import ChangeFace, imgSize
import random
import time
import string
from PIL import Image


class Index(View):

    def get(self, request):

        return render(request, 'index.html')

    def post(self, request):

        # 获取IP
        if 'HTTP_X_FORWARDED_FOR' in request.META:
            user_ip = request.META['HTTP_X_FORWARDED_FOR']
        else:
            user_ip = request.META['REMOTE_ADDR']

        # 获取图片
        img1 = request.FILES.get('pic1')
        img2 = request.FILES.get('pic2')

        if not all([img1, img2]):
            context = {
                'errmsg': '请先上传照片再点开始！'
            }
            return render(request, 'index.html', context=context)

        # 备份
        a = string.ascii_uppercase + string.digits
        key = random.sample(a, 6)
        keys = ''.join(key)
        localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        backup_path = 'static/backup/'
        with open(backup_path + str(keys) + '_' + str(localtime) + '_' + user_ip + '_' + img1.name, 'wb') as f:
            for content in img1.chunks():
                f.write(content)
        with open(backup_path + str(keys) + '_' + str(localtime) + '_' + user_ip + '_' + img2.name, 'wb') as f:
            for content in img2.chunks():
                f.write(content)

        save_path = 'static/img/'
        with open(save_path + 'a.jpg', 'wb') as f:
            for content in img1.chunks():
                f.write(content)
        with open(save_path + 'b.jpg', 'wb') as f:
            for content in img2.chunks():
                f.write(content)

        # 如果图片太大则修改尺寸
        imgSize.imgSize(save_path + 'a.jpg', save_path + 'a.jpg')
        imgSize.imgSize(save_path + 'b.jpg', save_path + 'b.jpg')

        try:
            # 换脸
            ChangeFace.change_face('static/img/a.jpg', 'static/img/b.jpg')
            # img3_data = open('static/img/c.jpg', "rb").read()

            # 备份生成后的照片
            img3 = Image.open('static/img/c.jpg')
            img3.save(backup_path + str(keys) + '_c.jpg')

            context = {
                'imgSrc': backup_path + str(keys) + '_c.jpg',
                'errmsg': '恭喜换脸成功，从此走上人生巅峰！'
            }
            print(context['imgSrc'])

            return render(request, 'result.html', context=context)
        except (IndexError, ValueError):
            context = {
                'errmsg': '换脸失败，未检测到脸部数据！'
            }
            return render(request, 'index.html', context=context)
        except IOError:
            context = {
                'errmsg': '没有找到文件或读取文件失败！'
            }
            return render(request, 'index.html', context=context)

        except PIL.UnidentifiedImageError:
            context = {
                'errmsg': '未知错误！'
            }
            return render(request, 'index.html', context=context)

